'use strict';
const db = uniCloud.database();
const dbCmd = db.command;

exports.main = async (event, context) => {
  const { user_id } = event;
  try {
    if (!user_id) {
      return { code: -1, msg: '用户ID不能为空' };
    }

    const pkCollection = db.collection('pk_records');
    const userCollection = db.collection('users');

    const pkRes = await pkCollection
      .where({
        opponent_id: user_id,
        challenger_id: dbCmd.neq(user_id),
        status: 'pending'
      })
      .get();

    console.log('待接受挑战查询结果:', pkRes.data);

    const challenges = [];
    for (const pk of pkRes.data) {
      const challengerRes = await userCollection.doc(pk.challenger_id).get();
      const challenger = challengerRes.data || { name: '未知用户', _id: pk.challenger_id };
      challenges.push({
        pk_id: pk._id,
        challenger_id: pk.challenger_id,
        challenger_name: challenger.name,
        created_at: pk.created_at
      });
    }

    return {
      code: 0,
      data: challenges,
      msg: '获取待接受挑战成功'
    };
  } catch (e) {
    console.error('获取待接受挑战失败:', e);
    return { code: -1, msg: `获取待接受挑战失败: ${e.message || '未知错误'}` };
  }
};